/*
 * Copyright 2011 Marcos Fabio Pereira
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.moveme.network;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;

import com.moveme.MoveMeListener;
import com.moveme.network.payload.PSMoveServerPacketHeader;
import com.moveme.network.payload.PSPayload;
import com.moveme.network.payload.PayloadConstants;
import com.moveme.network.payload.cameraslice.PSCameraFrameSlice;

/**
 * The UDP client that receives and process the packets from MoveMe server.
 * 
 * @author Marcos Fabio Pereira
 * 
 */
public class UdpClient implements Runnable {

    /**
     * The max size of a packet received from MoveMe server.
     */
    public static int MAX_PACKET_SIZE = 65536;

    /**
     * Set the UDP client to run or not.
     */
    private boolean running;

    /**
     * Listener to receive the processed data.
     */
    protected final MoveMeListener udpClientListener;

    /**
     * Local port.
     */
    private final int localPort;

    /**
     * A thread pool to forward the incoming UDP packages.
     */
    private final ExecutorService pool;

    /**
     * UDP client constructor.
     * 
     * @param localPort
     *            The local port to receive the data from MoveMe server.
     * @param udpClientListener
     *            UDP listener to receive the processed data.
     */
    public UdpClient(int localPort, MoveMeListener udpClientListener) {
        this.localPort = localPort;
        this.udpClientListener = udpClientListener;
        this.pool = Executors.newCachedThreadPool();
    }

    @Override
    public void run() {
        this.running = true;
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(this.localPort);
        } catch (SocketException e) {
            this.udpClientListener.notifyError(e);
        }

        byte[] byteArrayPacket = new byte[MAX_PACKET_SIZE];
        DatagramPacket datagramPacket = new DatagramPacket(byteArrayPacket,
                MAX_PACKET_SIZE);
        while (running) {
            try {
                datagramSocket.receive(datagramPacket);
                ByteBuffer bBuff = ByteBuffer.allocate(MAX_PACKET_SIZE);
                bBuff.put(byteArrayPacket);
                this.pool.execute(new UdpClientProcessData(byteArrayPacket, this));
            } catch (IOException e) {
                this.udpClientListener.notifyError(e);
            }
        }
    }

    /**
     * Stop the execution of the udp client.
     */
    public void stop() {
        this.running = false;
    }

    /**
     * Get the local port of the udp client.
     * 
     * @return int Local port.
     */
    public int getLocalPort() {
        return this.localPort;
    }

    /**
     * Get the current listener for the udp client.
     * 
     * @return MoveMeListener The current listener.
     */
    public MoveMeListener getListener() {
        return this.udpClientListener;
    }

}

/**
 * Process the data received by MoveMe server in another thread.
 * 
 * @author Marcos Fabio Pereira
 * 
 */
class UdpClientProcessData implements Runnable {

    /**
     * The data to be processed.
     */
    private byte[] data;

    /**
     * The listener
     */
    private UdpClient udpClient;

    public UdpClientProcessData(byte[] data, UdpClient udpClient) {
        this.data = data.clone();
        this.udpClient = udpClient;
    }

    @Override
    public void run() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(UdpClient.MAX_PACKET_SIZE);
        byteBuffer.put(data);
        int magic = byteBuffer.getInt(0);
        if (PayloadConstants.PSMOVE_PACKET_MAGIC == magic) {
            PSMoveServerPacketHeader header = new PSMoveServerPacketHeader(
                    byteBuffer);
            PSPayload udpClientPayload = PSPayload
                    .createInstance(header.payloadCode);
            udpClientPayload.setHeader(header);
            udpClientPayload.processBody(byteBuffer);
            if (udpClientPayload.header.payloadCode != PSMoveServerPacketHeader.CAMERA_FRAME_CODE) {
                this.udpClient.udpClientListener.processData(udpClientPayload);
            } else {
                PSCameraFrameSlice cameraFrameSlice = (PSCameraFrameSlice) udpClientPayload;
                // If it is a CAMERA_FRAME_CODE, must cast the
                // udpClientPayload and get the data.
                Image img = null;
                try {
                    img = ImageIO.read(new ByteArrayInputStream(
                            cameraFrameSlice.imageData));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                this.udpClient.udpClientListener.processImage(img);
            }
        }
    }

}
